package net.tmaize.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 根据Properties得到api地址
 * 
 * @author 宇明
 *
 */
public class ApiUtils {

	public static String latestURL;
	public static String hotURL;
	public static String beforeURL;
	public static String detailURL;

	/**
	 * 静态初始化器
	 */
	static {
		try {
			latestURL = getApiUrl("latest");
			hotURL = getApiUrl("hot");
			beforeURL = getApiUrl("before");
			detailURL = getApiUrl("detail");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static String getApiUrl(String type) throws IOException {
		StringBuffer sb = new StringBuffer();
		sb.append(getPropertiesValue("host"));
		sb.append(getPropertiesValue("verson"));
		sb.append(getPropertiesValue(type));
		return sb.toString();
	}

	// Servlet类可以采用getServletContext().getResourceAsStream()
	// 非Servlet类可以采下面的方法：
	// 1.1类装载器,弊端，只装载一次，当文件变动后不能生效,文件不能太大
	// Thread.currentThread().getContextClassLoader().getResourceAsStream
	// 1.2类装载器
	// ApiUtils.class.getClassLoader().getResourceAsStream("/zh_api.properties");
	// 2.获取绝对路径
	public static String getPropertiesValue(String name) throws IOException {
		InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("zhAPI.properties");
		// inputStream =
		Properties properties = new Properties();
		properties.load(inputStream);
		return properties.getProperty(name);
	}
}
